import math
import random
from constants import *

class Tank:
    def __init__(self, x, y, color, is_player=True):
        self.x = x
        self.y = y
        self.color = color
        self.is_player = is_player

        # 坦克属性
        self.width = TANK_WIDTH
        self.height = TANK_HEIGHT
        self.health = INITIAL_HEALTH
        self.ammo = INITIAL_AMMO

        # 角度（度数）
        self.angle = PLAYER_INITIAL_ANGLE if is_player else \
                    random.randint(ENEMY_INITIAL_ANGLE_MIN, ENEMY_INITIAL_ANGLE_MAX)
        self.cannon_angle = self.angle  # 炮管角度初始与坦克方向一致

        # 移动和旋转状态
        self.speed = PLAYER_SPEED if is_player else ENEMY_SPEED
        self.rotation_speed = 0
        self.cannon_rotation_speed = 0

        # 上次发射时间
        self.last_fire_time = 0

        # 新增：控制坦克行为的标志
        self.can_move = True
        self.can_fire_bullet = True

    def draw(self, screen):
        # 绘制坦克主体（圆角矩形）
        tank_surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        pygame.draw.rect(tank_surface, self.color,
                        (0, 0, self.width, self.height),
                        border_radius=TANK_CORNER_RADIUS)

        # 旋转坦克主体
        rotated_tank = pygame.transform.rotate(tank_surface, -self.angle)
        tank_rect = rotated_tank.get_rect(center=(self.x, self.y))
        screen.blit(rotated_tank, tank_rect)

        # 绘制炮塔（圆形）
        pygame.draw.circle(screen, self.color, (self.x, self.y), TURRET_RADIUS)

        # 绘制炮管
        cannon_end_x = self.x + math.cos(math.radians(self.cannon_angle)) * CANNON_LENGTH
        cannon_end_y = self.y - math.sin(math.radians(self.cannon_angle)) * CANNON_LENGTH
        pygame.draw.line(screen, self.color,
                        (self.x, self.y),
                        (cannon_end_x, cannon_end_y),
                        4)

    def move(self, forward=True):
        """移动坦克"""
        if not self.can_move:
            return False

        direction = 1 if forward else -1
        angle_rad = math.radians(self.angle)
        self.x += math.cos(angle_rad) * TANK_MOVE_DISTANCE * direction
        self.y -= math.sin(angle_rad) * TANK_MOVE_DISTANCE * direction

        # 确保坦克不会超出屏幕边界
        self.x = max(self.width/2, min(WINDOW_WIDTH - self.width/2, self.x))
        self.y = max(self.height/2, min(WINDOW_HEIGHT - self.height/2, self.y))

        # 返回移动状态
        return True

    def rotate(self, clockwise=True):
        """旋转坦克"""
        direction = -1 if clockwise else 1
        self.angle = (self.angle + TANK_ROTATION_ANGLE * direction) % 360
        # 炮管跟随坦克旋转
        self.cannon_angle = (self.cannon_angle + TANK_ROTATION_ANGLE * direction) % 360

    def rotate_cannon(self, clockwise=True):
        """旋转炮管"""
        direction = -1 if clockwise else 1
        new_angle = (self.cannon_angle + CANNON_ROTATION_ANGLE * direction) % 360

        # 检查炮管是否在允许的范围内
        angle_diff = (new_angle - self.angle) % 360
        if angle_diff <= 90 or angle_diff >= 270:
            self.cannon_angle = new_angle

    def can_fire(self):
        """检查是否可以发射炮弹"""
        current_time = pygame.time.get_ticks()
        fire_interval = 1000 / (PLAYER_FIRE_RATE if self.is_player else ENEMY_FIRE_RATE)
        return (current_time - self.last_fire_time >= fire_interval) and (self.ammo > 0)

    def fire(self):
        """发射炮弹"""
        if not self.can_fire_bullet or not self.can_fire():
            return None

        self.last_fire_time = pygame.time.get_ticks()
        self.ammo -= 1
        return self.get_cannon_end()

    def get_cannon_end(self):
        """获取炮管末端坐标"""
        angle_rad = math.radians(self.cannon_angle)
        end_x = self.x + math.cos(angle_rad) * CANNON_LENGTH
        end_y = self.y - math.sin(angle_rad) * CANNON_LENGTH
        return end_x, end_y, self.cannon_angle

    def take_damage(self, amount):
        """受到伤害"""
        self.health = max(0, self.health - amount)
        return self.health <= 0

    def update(self, can_move=True, can_fire=True):
        """更新坦克状态"""
        self.can_move = can_move
        self.can_fire_bullet = can_fire
        fired = None
        is_moving = False

        if not self.is_player and self.can_move:
            # 敌方坦克的简单AI逻辑
            if random.random() < 0.02:  # 2%的概率改变方向
                self.rotate(clockwise=random.choice([True, False]))
                is_moving = True
            if random.random() < 0.05:  # 5%的概率移动
                is_moving = self.move(forward=random.choice([True, False]))
            if random.random() < 0.01 and self.can_fire_bullet:  # 1%的概率尝试开火
                fired = self.fire()
        return fired, is_moving